﻿using Common.MyCustomException;
using Common.Utils;
using IService;
using Model.Dto.Users;
using Model.Entitys;
using SqlSugar;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    public class UserService : IUserService
    {
        private readonly ISqlSugarClient _db;
        private readonly IConnectionMultiplexer _redis;
        public UserService(ISqlSugarClient db, IConnectionMultiplexer redis)
        {
            _db = db;
            _redis = redis;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<User> LoginAsync(UserLogin userLogin)
        {
            var rdb = _redis.GetDatabase(1);
            //获取保存的验证码
            var dbCode =await rdb.StringGetAsync(userLogin.Phone);
            //进行验证码的比对
            if (dbCode != RedisValue.Null && dbCode == userLogin.Code)
            {
                var user=await _db.Queryable<User>().FirstAsync(it => it.Phone == userLogin.Phone);
                if (user == null)
                {
                    //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                    user = new User()
                    {
                        Name=Guid.NewGuid().ToString(),
                        Phone= userLogin.Phone,
                        Status=1
                    };
                    long id = _db.Insertable(user).ExecuteReturnSnowflakeId();
                }
                //删除验证码
                await rdb.KeyDeleteAsync(userLogin.Phone);
                return user;
            }
            throw new MyCustomException("登录失败");
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        public async Task<bool> SendMsgAsync(UserLogin userLogin)
        {
            if (!string.IsNullOrEmpty(userLogin.Phone))
            {
                //生成随机的4位验证码
                string code = RandomNumberGenerator.Generate(4);
                Console.WriteLine($"验证码为:{code}");
                //调用阿里云提供的短信服务API完成发送短信
                //AliyunSmsApi.SendSms(userLogin.Phone, code);
                //需要将生成的验证码保存到redis
                var rdb = _redis.GetDatabase(1);
                await rdb.StringSetAsync(userLogin.Phone, code);
                //验证码有效期5分钟
                await rdb.KeyExpireAsync(userLogin.Phone, TimeSpan.FromSeconds(300));
                return true;
            }
            return false;
        }
    }
}
